import React, { Children, Component } from 'react';
import {
  Row,
  Col,
  Card,
  List,
  Avatar,
  Button,
  Form,
  Popconfirm,
  Divider,
  Modal,
  Slider,
  InputNumber,
  Collapse,
  Icon,
  message,
  Select,
  Timeline,
  Input,
} from 'antd';
import Link from 'umi/link';
import { formatMessage } from 'umi/locale';
import { connect } from 'dva';
import EapParamsForm from './hdForms/EapParamsForm';
import ParamVerifyForm_01 from './hdForms/ParamVerifyForm_01';
import ParamVerifyForm_02 from './hdForms/ParamVerifyForm_02';
import UserVerifyForm from './hdForms/UserVerifyForm';
import { Stage, Layer, Text, Image, Line, Label, Tag, Rect } from 'react-konva';
import EapParamsFormExtend from './hdForms/EapParamsFormExtend';
import ProductionInfoDownloadForm from './hdForms/ProductionInfoDownloadForm';
import LotCommandDownloadForm from './hdForms/LotCommandDownloadForm';
import CimMessageForm from './hdForms/CimMessageForm';

@connect(({ produce, es }) => ({ produce, es }))
@Form.create()
class EapSocket extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    userId: '',
    clockType: 'ClockIn',
    verify_lot_id: '',
    requestOptionVal: 'AreYouThere',
    searchId: '',
    reqSelectOpList: [
      'AreYouThere',
      'CIMModeChangeReport',
      'JobCountReport',
      'AlarmReport',
      'ParamVerify',
      'RealStatusReport',
      'StatusChangeReport',
      'UserVerify',
      'WIPTrackingReport',
      'UtilityReport',
      'EquipmentCurrentLotReport',
    ],
  };

  UserVerify = e => {
    const { dispatch } = this.props;
    const { userId, clockType } = this.state;
    dispatch({
      type: 'es/userVerifyRequest',
      payload: [userId, clockType],
    });
  };

  ParamVerifyRequest = e => {
    const { dispatch } = this.props;
    const { verify_lot_id } = this.state;
    dispatch({
      type: 'es/paramVerifyRequest',
      payload: verify_lot_id,
    });
  };

  closeCimMessageHistory = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/updateCimMessageHistory',
      payload: [false, []],
    });
  };

  manualFinish = e => {
    const { dispatch } = this.props;
    const { searchId } = this.state;
    dispatch({
      type: 'es/manualFinish',
      payload: searchId,
    });
  };

  closeCimMessageModal = e => {
    const { dispatch } = this.props;
    this.closeCimMessageUI();
    dispatch({
      type: 'es/closeCimMessageModal',
    });
  };

  closeCimMessageUI = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/closeCimMessageModalUI',
    });
  };
  cimMessageHistory = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/cimMessageHistory',
    });
  };

  mockReqeustClick = e => {
    const { dispatch } = this.props;
    const { requestOptionVal } = this.state;
    dispatch({
      type: 'es/mockReqeustClick',
      payload: requestOptionVal,
    });
  };

  openEapDebugDir = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logger/openDebugDir',
    });
  };

  clearProductionInfoDownload = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/clearProductionInfoDownload',
    });
  };

  chooseEapLogDir = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/chooseEapLogDir',
    });
  };

  onClockOptionChange = (key, e) => {
    this.setState({
      clockType: e.props.children,
    });
  };

  onRequestOptionChange = (key, e) => {
    this.setState({
      requestOptionVal: e.props.children,
    });
  };
  closeParamVerifyModal = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/closeParamVerifyModal',
    });
  };
  closeUserVerifyModal = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'es/closeUserVerifyModal',
    });
  };

  // 搜索下拉框的值改变的时候searchId会跟着变.
  onChange = (key, e) => {
    this.setState({
      searchId: e.props.children,
    });
  };

  render() {
    const Panel = Collapse.Panel;
    const {
      eapIsOnline,
      cimMessageVisible,
      cimMessage,
      cimMessageType,
      timeStamp,
      showTimeLeft,
      serverEapParams,
      dataJsonSend,
      dataJsonReceive,
      response_result,
      return_code,
      return_msg,
      pvrModalVisible,
      serverParamVirifyRes,
      current_login_user_id,
      serverUserVirifyRes,
      userVrModaVisible,
      eapProdinfoDownload,
      lotCommandDownload,
      cimMessageHistoryVisible,
      cimMessageHistory,
    } = this.props.es;
    const { reqSelectOpList, verify_lot_id, userId } = this.state;

    const requestSelectOptions = [];
    for (let i = 0; i < reqSelectOpList.length; i++) {
      requestSelectOptions.push(
        <Select.Option key={i.toString() + i}>{reqSelectOpList[i]}</Select.Option>
      );
    }

    const children = [];
    for (let i = 0; i < lotCommandDownload.length; i++) {
      children.push(<Option key={i.toString() + i}>{lotCommandDownload[i]['lot_id']}</Option>);
    }

    const gridStyle1 = {
      width: '20%',
      textAlign: 'left',
    };
    const gridStyle2 = {
      width: '80%',
      textAlign: 'left',
    };

    const containerStyle = {
      display: 'flex',
      marginTop: 50,
    };
    const cardStyleLeft = {
      flex: '0 0 21%', // 左侧Card占用20%
      marginRight: '10px', // 右边间距
      height: '800px',
    };

    const cardStyleRight = {
      flex: '0 0 79%', // 右侧Card占用80%
    };

    const textAreaStyle = {
      width: '100%',
      height: '350px', // 固定文本框的高度
      fontSize: '14px', // 文本字体大小
      overflowY: 'auto', // 当内容超出高度时出现滚动条
      padding: '5px',
      marginTop: '5px',
      marginBottom: '5px',
      border: '1px solid #ccc',
      borderRadius: '4px',
      whiteSpace: 'pre-wrap',
    };

    return (
      <div style={containerStyle}>
        <Card style={cardStyleLeft}>
          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 18 }}>Send</span>
          <div style={textAreaStyle}>{JSON.stringify(dataJsonSend, null, 4)}</div>
          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 18 }}>Receive</span>
          <div style={textAreaStyle}>{JSON.stringify(dataJsonReceive, null, 4)}</div>
        </Card>

        <Card style={cardStyleRight}>
          <Row>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16 }}>
              {formatMessage({ id: 'app.eap.status.label' })}:
            </span>{' '}
            {eapIsOnline ? (
              <font style={{ color: '#00FF00', fontSize: 18 }}>
                {formatMessage({ id: 'app.eap.status.online' })}
              </font>
            ) : (
              <font style={{ color: '#FF0000', fontSize: 18 }}>
                {formatMessage({ id: 'app.eap.status.offline' })}
              </font>
            )}{' '}
            <Select
              style={{ width: 200, marginLeft: 20 }}
              onChange={this.onRequestOptionChange}
              defaultValue={reqSelectOpList[0]}
            >
              {requestSelectOptions}
            </Select>
            <Button style={{ marginLeft: 10 }} onClick={this.mockReqeustClick}>
              {formatMessage({ id: 'app.eap.mockRequest.button' })}
            </Button>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
              {formatMessage({ id: 'app.eap.result.label' })}
            </span>
            <Input value={response_result} style={{ marginLeft: 5, width: 80 }} disabled />
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
              {formatMessage({ id: 'app.eap.returnCode.label' })}
            </span>
            <Input value={return_code} style={{ marginLeft: 5, width: 150 }} disabled />
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
              {formatMessage({ id: 'app.eap.returnMsg.label' })}
            </span>
            <Input value={return_msg} style={{ marginLeft: 5, width: 250 }} disabled />
          </Row>
          <hr style={{ border: '1px solid #ccc', margin: '15px 0' }} />
          <Row>
            <div style={{ marginBottom: 8 }}>
              <span style={{ color: 'green', fontWeight: 'bold', fontSize: 18 }}>
                {formatMessage({ id: 'app.eap.params.config.label' })}
              </span>
            </div>
            <EapParamsForm serverEapParams={serverEapParams} />
          </Row>
          <Row style={{ marginTop: 8, display: 'flex', alignItems: 'center', flexWrap: 'wrap' }}>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16 }}>
              {formatMessage({ id: 'app.eap.log.saveDir.label' })}
            </span>
            <Button style={{ marginLeft: 10 }} onClick={this.chooseEapLogDir}>
              {formatMessage({ id: 'app.eap.log.chooseDir.button' })}
            </Button>

            <span style={{ marginLeft: 20, color: 'green', fontWeight: 'bold', fontSize: 16 }}>
              {formatMessage({ id: 'app.eap.debug.currentDir.label' })}
            </span>
            <Input
              value={(serverEapParams && serverEapParams[0] && serverEapParams[0].eapLogDir) || ''}
              readOnly
              style={{ marginLeft: 10, width: 420, fontSize: 12 }}
            />
            <Button style={{ marginLeft: 10 }} onClick={this.openEapDebugDir}>
              {formatMessage({ id: 'app.eap.debug.openDir.button' })}
            </Button>
          </Row>
          <Row style={{ marginTop: 5 }}>
            <EapParamsFormExtend serverEapParams={serverEapParams} />
          </Row>
          <hr style={{ border: '1px solid #ccc', margin: '15px 0' }} />
          <Row>
            <div style={{ marginBottom: 10 }}>
              <span style={{ color: 'green', fontWeight: 'bold', fontSize: 18 }}>
                {formatMessage({ id: 'app.eap.paramVerify.userVerify.title' })}
              </span>

              <Button style={{ marginLeft: 50 }} onClick={this.cimMessageHistory}>
                {formatMessage({ id: 'app.eap.cimMessageHistory.button' })}
              </Button>
            </div>
            {formatMessage({ id: 'app.eap.lotId.label' })}
            <Input
              onChange={e => this.setState({ verify_lot_id: e.target.value })}
              style={{ marginLeft: 5, width: 180, fontSize: 12 }}
            />
            <Button style={{ marginLeft: 10 }} onClick={this.ParamVerifyRequest}>
              {formatMessage({ id: 'app.eap.paramVerify.button' })}
            </Button>
            <span style={{ marginLeft: 40 }}>
              {formatMessage({ id: 'app.eap.userKeyinUserId.label' })}
            </span>
            <Input
              onChange={e => this.setState({ userId: e.target.value })}
              style={{ marginLeft: 5, width: 180, fontSize: 12 }}
            />
            <span style={{ marginLeft: 20 }}>
              {formatMessage({ id: 'app.eap.clockType.label' })}
            </span>
            <Select
              style={{ width: 200, marginLeft: 10 }}
              onChange={this.onClockOptionChange}
              defaultValue="ClockIn"
            >
              <Select.Option value="ClockIn">ClockIn</Select.Option>
              <Select.Option value="ClockOut">ClockOut</Select.Option>
              <Select.Option value="Query">Query</Select.Option>
            </Select>
            <Button style={{ marginLeft: 10 }} onClick={this.UserVerify}>
              {formatMessage({ id: 'app.eap.userVerify.button' })}
            </Button>
            <span style={{ marginLeft: 40 }}>{formatMessage({ id: 'app.eap.userId.label' })}</span>
            <Input
              value={current_login_user_id}
              style={{ marginLeft: 5, width: 180, fontSize: 12 }}
              readOnly
            />
          </Row>
          <hr style={{ border: '1px solid #ccc', margin: '20px 0px' }} />
          <Row>
            <div style={{ marginBottom: 8 }}>
              <span style={{ color: 'green', fontWeight: 'bold', fontSize: 18 }}>
                LotCommandDownload {formatMessage({ id: 'app.eap.taskQueue.label' })}{' '}
              </span>

              <span style={{ marginLeft: 10, color: 'orange', fontSize: 16 }}>
                {formatMessage({ id: 'app.eap.lotId.label' })}:
              </span>
              <Select
                showSearch
                style={{ width: 200, marginLeft: 10 }}
                optionFilterProp="children"
                onChange={this.onChange}
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {children}
              </Select>
              <Button onClick={this.manualFinish} style={{ marginLeft: 10, marginRight: 10 }}>
                {formatMessage({ id: 'app.produce.manualFinish' })}
              </Button>
            </div>
            <LotCommandDownloadForm lotCommandDownload={lotCommandDownload} />
          </Row>
          <hr style={{ border: '1px solid #ccc', margin: '20px 0px' }} />
          <Row>
            <div style={{ marginBottom: 8 }}>
              <span style={{ color: 'green', fontWeight: 'bold', fontSize: 18 }}>
                Production Info Download {formatMessage({ id: 'app.eap.taskQueue.label' })}{' '}
              </span>
              <Button style={{ marginLeft: 20 }} onClick={this.clearProductionInfoDownload}>
                {formatMessage({ id: 'app.eap.clearQueue.button' })}
              </Button>
            </div>
            <ProductionInfoDownloadForm eapProdinfoDownload={eapProdinfoDownload} />
          </Row>
        </Card>

        <Modal
          title={'EAP远程讯息提示框'}
          visible={cimMessageVisible}
          width={window.screen.availWidth - 700}
          closable={false}
          footer={[
            <Button key="close" type="primary" onClick={this.closeCimMessageModal}>
              Close CimMessage Modal
            </Button>,
          ]}
        >
          <Row>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 10 }}>
              messageType:
            </span>
            <span style={{ color: 'orange', fontWeight: 'bold', fontSize: 16, marginLeft: 15 }}>
              {cimMessageType}
            </span>
          </Row>
          <Row style={{ marginTop: 10 }}>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 10 }}>
              messageContent:
            </span>
            <span style={{ color: 'orange', fontWeight: 'bold', fontSize: 16, marginLeft: 15 }}>
              {cimMessage}
            </span>
          </Row>
          <Row style={{ marginTop: 10 }}>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 10 }}>
              timeStamp:
            </span>
            <span style={{ color: 'orange', fontWeight: 'bold', fontSize: 16, marginLeft: 15 }}>
              {timeStamp}
            </span>
          </Row>
          <Row style={{ marginTop: 10 }}>
            <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 10 }}>
              Will Close After:
            </span>
            <span style={{ color: 'orange', fontWeight: 'bold', fontSize: 16, marginLeft: 15 }}>
              {showTimeLeft}
            </span>
          </Row>
        </Modal>

        <Modal
          title={formatMessage({ id: 'app.eap.paramVerify.result.title' })}
          visible={pvrModalVisible}
          width={window.screen.availWidth - 600}
          closable={false}
          footer={[
            <Button key="close" type="primary" onClick={this.closeParamVerifyModal}>
              {formatMessage({ id: 'app.tools.Close' })}
            </Button>,
          ]}
        >
          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
            Result
          </span>
          <Input value={response_result} style={{ marginLeft: 5, width: 80 }} disabled />
          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
            Return Code
          </span>
          <Input value={return_code} style={{ marginLeft: 5, width: 150 }} disabled />

          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
            Return Msg
          </span>
          <Input value={return_msg} style={{ marginLeft: 5, width: 250 }} disabled />
          <hr style={{ border: '1px solid #ccc', margin: '15px 0' }} />
          <Row>
            <ParamVerifyForm_01
              key="serverParamVirifyRes01"
              serverParamVirifyRes01={serverParamVirifyRes}
            />
          </Row>
          <Row style={{ marginTop: 20 }}>
            <ParamVerifyForm_02
              key="serverParamVirifyRes02"
              serverParamVirifyRes02={serverParamVirifyRes}
            />
          </Row>
        </Modal>

        <Modal
          title={formatMessage({ id: 'app.eap.userVerify.result.title' })}
          visible={userVrModaVisible}
          width={window.screen.availWidth - 600}
          closable={false}
          footer={[
            <Button key="close" type="primary" onClick={this.closeUserVerifyModal}>
              {formatMessage({ id: 'app.tools.Close' })}
            </Button>,
          ]}
        >
          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
            Result
          </span>
          <Input value={response_result} style={{ marginLeft: 5, width: 80 }} disabled />
          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
            Return Code
          </span>
          <Input value={return_code} style={{ marginLeft: 5, width: 150 }} disabled />

          <span style={{ color: 'green', fontWeight: 'bold', fontSize: 16, marginLeft: 20 }}>
            Return Msg
          </span>
          <Input value={return_msg} style={{ marginLeft: 5, width: 250 }} disabled />
          <hr style={{ border: '1px solid #ccc', margin: '15px 0' }} />
          <Row>
            <UserVerifyForm key="serverUserVirifyRes" serverUserVirifyRes={serverUserVirifyRes} />
          </Row>
        </Modal>

        <Modal
          title={formatMessage({ id: 'app.eap.cimMessageHistory.title' })}
          visible={cimMessageHistoryVisible}
          width={window.screen.availWidth - 600}
          closable={false}
          footer={[
            <Button key="close" type="primary" onClick={this.closeCimMessageHistory}>
              Close
            </Button>,
          ]}
        >
          <Row>
            <CimMessageForm key="cimMessageHistory" cimMessageHistory={cimMessageHistory} />
          </Row>
        </Modal>
      </div>
    );
  }
}
export default EapSocket;
